import {View} from "@tarojs/components";
import DynamicForm, {FormConfig, OptionConfig} from "@/components/DynamicForm";
import AssetImage from "@/common/AssetImage";
import {useCallback, useEffect, useRef, useState} from "react";
import {
  getTeamRechargeParamsApi,
  getUserRechargeParamsApi, invoiceApplyApi,
  invoiceListApi,
} from "@/common/apis/home_datasource";
import Utils from "@/utils/common";
import {InvoiceParams} from "@/common/apis/model";
import {Empty} from "@antmjs/vantui";
import ShowUtils from "@/utils/show_utils";
import Taro from "@tarojs/taro";
import EventUtils from "@/utils/event_utils";
import LocalData from "@/common/local_data";
import RouthPath from "@/common/RouthPath";

definePageConfig({
  navigationBarTitleText: ''
})

export default function ApplyRecharge() {

  const [fromConfigs, setFromConfigs] = useState<FormConfig[]>();

  const initValues = useRef({});
  const btnText = useRef<String>();

  const getFromConfig = useCallback((infoOptions: Array<OptionConfig>) => {
    if (!infoOptions) return null
    const isRecharge = invoiceParams.current?.type === 1;
    const config: FormConfig[] = [
      {
        type: 'input',
        inputType: LocalData.numInputType,
        name: 'amount', // Logical name for recipient name
        label: isRecharge ? '充值金额' : '发票金额',       // Label text (without *)
        placeholder: isRecharge ? '请填写充值金额' : '请填写发票金额',
        layout: 'vertical',
        required: true,        // Has asterisk
        rules: []
      },
      {
        type: 'picker',
        name: 'invoiceId', // Logical name for contact phone
        label: '开票信息',     // Label text (without *)
        placeholder: '请选择开票信息',
        required: true,        // Has asterisk
        options: infoOptions,
        rules: []
      },
      {
        // Although it's address, the UI shows a single-line input field style
        type: 'picker',
        name: 'invoiceType', // Logical name for the detailed address
        label: '发票类型',       // Label text (without *)
        placeholder: '请发票类型',
        required: true,        // Has asterisk
        options: [
          {label: '普票(电子) ', text: '普票(电子) ', value: '0'},
          {label: '专票（电子）', text: '专票（电子）', value: '1'},
        ],
        rules: []
      },
      {
        type: 'checkbox',
        name: 'fileType',
        label: '需要的资料',
        layout: 'vertical',
        options: LocalData.needContent,
      },
      {
        type: 'textarea',
        name: 'note',
        label: '开票要求',
        layout: 'vertical',
        placeholder: '请输入开票要求',
        minHeight: "200px",
        maxlength: 200,
        inputBgColor: AssetImage.bg,
        showWordLimit: true
      },
    ];
    return config
  }, []);

  const invoiceParams = useRef<InvoiceParams>();


  const channelEvent = useRef<Taro.EventChannel | null>();

  useEffect(() => {
    const instance = Utils.getI();
    const p = Utils.getParamsByRouter(instance);
    channelEvent.current = Utils.getChannel(instance)
    if (p && p.data) {
      invoiceParams.current = Utils.getObjectWithUrl<InvoiceParams>(p.data)
      if (invoiceParams.current?.item) {
        const orderItem = invoiceParams.current?.item;
        initValues.current = {
          amount: orderItem?.actualAmount,
          note: orderItem?.projectName,
        }
      } else if (invoiceParams.current?.name) {
        const name = invoiceParams.current?.name;
        initValues.current = {
          note: name,
        }
      }
    }
    const type = invoiceParams.current?.type;
    //title 1充值 0，2申请发票
    if (type === 1) {
      Utils.setTitle(invoiceParams.current?.teamId ? '组充值' : '充值')
      btnText.current = '立即充值'
    } else {
      Utils.setTitle('申请发票')
      btnText.current = '申请发票'
    }
    //获取发票列表，设置上面
    invoiceListApi().then(invoiceList => {
      if (invoiceList) {
        if (invoiceList.length === 0) {
          Utils.modal('提示', '您还没有发票信息，请先去添加发票信息', true, (ok) => {
            if (ok) {
              Utils.redirectTo({ // Or Taro.redirectTo
                url: RouthPath.addFapiao,
              });
            } else {
              Utils.navigateBack()
            }
          })
          return
        }
        // 设置表单配置
        const list = invoiceList.map((invoice, index) => {
          return {label: `${invoice.title}(${invoice.no})`, text: `${invoice.title}(${invoice.no})`, value: invoice.id};
        })
        setFromConfigs(getFromConfig(list))
      }
    })
  }, [getFromConfig]);

  // 提交回调
  const handleSubmit = (values) => {
    console.log('Form values:', values);
    const type = invoiceParams.current?.type
    if (type === 1) {
      Utils.modal('提示', `确定要充值${ShowUtils.getDefaultPrice(values.amount)}`, true, (ok) => {
        if (ok) {
          let p = values
          if (values.fileType) {
            p = {...p, fileType: values.fileType.join(',')}
          }
          //是否加teamId
          if (invoiceParams.current?.teamId) {
            p = {...p, businessId: invoiceParams.current?.teamId}
          }
          const api = invoiceParams.current?.teamId ? getTeamRechargeParamsApi : getUserRechargeParamsApi;
          api(p).then((payParams) => {
            if (payParams) {
              Utils.payWx(payParams, (res) => {
                Utils.emit(channelEvent.current, EventUtils.ApplyRecharge, true)
                Utils.showOkToast('充值成功')
                Utils.navigateBack()
              })
            }
          })
        }
      })
    } else {
      let p = values
      if (values.fileType) {
        p = {...p, fileType: values.fileType.join(',')}
      }
      //申请发票
      if (invoiceParams.current?.item) {
        p = {...p, businessId: invoiceParams.current?.item.id}
      }
      invoiceApplyApi(p).then((res) => {
        if (res) {
          if (invoiceParams.current?.item) {
            Utils.emit(channelEvent.current, EventUtils.OK, true)
          }
          Utils.showOkToast('申请成功')
          Utils.navigateBack()
        }
      })
    }
    // 处理表单提交逻辑
  };

  // 错误回调
  const handleError = (errors) => {
    console.error('Form errors:', errors);
  };

  return (
    <View>
      {
        fromConfigs ? <DynamicForm
          initialValues={initValues.current}
          formConfigs={fromConfigs ? fromConfigs : []}
          onSubmit={handleSubmit}
          onError={handleError}
          submitText={btnText.current}
        /> : <Empty description='无'/>
      }
    </View>
  );
}


